﻿using DeathByCaptcha;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using VisaPoint.Entities;
using WatiN.Core;
using VisapointLibrary.Controllers;
using System.Net;
using System.Configuration;
using System.Net.Mail;
namespace VisaPoint.Controllers
{
    public class VisapointClientController
    {
        IEExtension browser;
        private long TickBetweenVisapointAndSystem = 0;
        private string IdNextButton = "ctl00_cp1_btnNext_input";
        private string IdPreButton = "ctl00_cp1_btnPrev_input";
        private string IdCaptchaDiv = "c_pages_form_cp1_captcha1_CaptchaImageDiv";
        //private MouseClick mouse = new MouseClick();
        private bool IsBack = false;
        private bool IsBegin = true;
        private bool IsFixLoadRun = true;
        public System.Windows.Forms.Timer timer;
        private int MinutesRefesh = 5;
        private int TimeRunWeb = 0;
        private AsynchronousClient client;
        private CaptchaSocket captchaSocket;
        public VISAPOINT_STATUS Status = VISAPOINT_STATUS.STOP;
        private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        public int Time = 0;
        public IVisapoint Visapoint { get; set; }
        public int SecondBeginRun { get; set; }
        /// <summary>
        /// Thời gian để load xong sang phần captcha
        /// </summary>
        public int TimeLoadStartRun { get; set; }
        /// <summary>
        /// Thời gian lấy captcha MAX
        /// </summary>
        public int TimeProcessCaptchaMAX { get; set; }
        /// <summary>
        /// Thời gian để web submit xong
        /// </summary>
        public int TimeSubmit { get; set; }
        /// <summary>
        /// Thời điểm bắt đầu 1 tiến trình
        /// </summary>
        public DateTime StartRun { get; set; }
        /// <summary>
        /// Thời điểm bắt đầu có captcha
        /// </summary>
        public DateTime StartCaptcha { get; set; }
        /// <summary>
        /// Thời điểm điền xong captcha và bắt đầu submit để check
        /// </summary>
        public DateTime StartSubmit { get; set; }
        /// <summary>
        /// Thời điểm hiện tại của Visapoint
        /// </summary>
        public DateTime TimeVisapoint { get { return DateTime.Now.AddTicks(TickBetweenVisapointAndSystem); } }
        public VISAPOINT_RESULT Result { get; set; }
        public Appointment AppointmentCurrent { get; set; }
        public EventHandler TimerHandler { get; set; }
        public TextBox txtTimeSubmit { get; set; }
        public VisapointClientController(IVisapoint visapoint, Appointment appointment, string IPServer, TextBox txtTimeSubmit)
        {
            this.txtTimeSubmit = txtTimeSubmit;
            timer = new System.Windows.Forms.Timer();
            timer.Interval = 1000;
            timer.Tick += new EventHandler(TimeTick);
            client = new AsynchronousClient(IPServer);
            captchaSocket = new CaptchaSocket();
            this.Visapoint = visapoint;
            this.AppointmentCurrent = appointment;
            InitData();
            MinutesRefesh = int.Parse(System.Configuration.ConfigurationManager.AppSettings["MinutesRefesh"].Trim());
            //captchaSocket.ConnectServer();
            //captchaSocket.start();

        }
        public void TimeTick(object sender, EventArgs e)
        {
            Time += 1;
            TimeRunWeb += 1;

            if (TimeRunWeb > MinutesRefesh * 60)
            {

                if (browser != null)
                {
                    WriteLog("Tắt web");
                    IsBegin = false;
                    //InitData();
                    if (txtTimeSubmit != null && !string.IsNullOrEmpty(txtTimeSubmit.Text))
                    {
                        TimeSubmit = 60 - int.Parse(txtTimeSubmit.Text);
                    }
                    TimeLoadStartRun = int.Parse(ConfigurationManager.AppSettings["TimeLoadStartRun"].Trim());
                    SecondBeginRun = 60 - (TimeLoadStartRun + TimeSubmit + TimeProcessCaptchaMAX);
                    cancellationTokenSource.Cancel();
                    browser.ClearCache();
                    browser.ClearCookies();
                    browser.Close();
                }
            }
            if (TimerHandler != null)
            {
                int hours = Time / 3600;
                int minutes = (Time % 3600) / 60;
                int seconds = Time - (hours * 3600 + minutes * 60);
                string stringTime = string.Format("{0}:{1}:{2}", (hours < 10) ? "0" + hours : hours + "", (minutes < 10) ? "0" + minutes : minutes + "", (seconds < 10) ? "0" + seconds : seconds + "");
                TimerHandler(stringTime, e);
            }
        }
        private void InitData()
        {
            TimeLoadStartRun = int.Parse(ConfigurationManager.AppSettings["TimeLoadStartRun"].Trim());
            TimeProcessCaptchaMAX = int.Parse(ConfigurationManager.AppSettings["TimeProcessCaptchaMAX"].Trim());
            TimeSubmit = int.Parse(ConfigurationManager.AppSettings["TimeSubmit"].Trim());
            SecondBeginRun = int.Parse(ConfigurationManager.AppSettings["SecondBeginRun"].Trim());
            IsFixLoadRun = bool.Parse(ConfigurationManager.AppSettings["IsFixLoadRun"].Trim());
            if (txtTimeSubmit != null && !string.IsNullOrEmpty(txtTimeSubmit.Text))
            {
                TimeSubmit = 60 - int.Parse(txtTimeSubmit.Text);
            }
        }

        public void TimerStart()
        {
            timer.Start();
        }
        public void Start()
        {
            try
            {


                Result = VISAPOINT_RESULT.NOTHING;
                //timer.Start();
                TimeRunWeb = 0;
                cancellationTokenSource = new CancellationTokenSource();
                while (Status == VISAPOINT_STATUS.RUNNING)
                {
                    //Neu la chay cac lan thu n>1 thi chờ
                    //if (!IsBegin)
                    //{
                    //    long timeWatingToStart = GetLongTimeWaiting(TimeVisapoint, SecondBeginRun);
                    //    //WriteLog("timeWating: " + timeWating);

                    //    if (!cancellationTokenSource.IsCancellationRequested)
                    //    {
                    //        cancellationTokenSource.Token.WaitHandle.WaitOne((int)timeWatingToStart);
                    //        //Thread.Sleep((int)timeWating);
                    //    }
                    //}

                    browser = new IEExtension("https://visapoint.eu/");
                    browser.BringToFront();
                    //Thiết lập ngôn ngữ
                    Div divLanguague = browser.Div(Find.ById("ctl00_ddLocale"));
                    divLanguague.Button(Find.ByClass("rcbActionButton")).Click();

                    Element elementLanguague = browser.Div(Find.ById("ctl00_ddLocale_DropDown")).Element(Find.ByText("Tiếng Việt"));
                    elementLanguague.Click();
                    //Click Xác nhận
                    browser.Button(Find.ById("ctl00_cp1_btnAccept_input")).Click();
                    //Click gửi đơn hẹn
                    browser.Button(Find.ById("ctl00_cp1_btnNewAppointment_input")).Click();
                    Div divCiti = browser.Div(Find.ById("ctl00_cp1_ddCitizenship"));
                    divCiti.Button(Find.ByClass("rcbActionButton")).Click();
                    // Điền Country
                    Element element = browser.Div(Find.ById("ctl00_cp1_ddCitizenship_DropDown")).Element(Find.ByText(AppointmentCurrent.Citizenship));
                    element.Click();
                    Div ddVisaType = browser.Div(Find.ById("ctl00_cp1_ddVisaType"));
                    ddVisaType.Button(Find.ByClass("rcbActionButton")).Click();

                    //Điền mục đích
                    Div VisaTypeDropDown = browser.Div(Find.ById("ctl00_cp1_ddVisaType_DropDown"));
                    VisaTypeDropDown.Element(Find.ByText(AppointmentCurrent.Purpose)).Click();

                    //*********Điền captcha lần đầu tiên
                FirstCaptcha:
                    StartCaptcha = DateTime.Now;
                    string fileCapchar = Application.StartupPath + @"\captcha.jpg";
                    WriteLog("Start get Capchar");
                    Div c_pages_form_cp1_captcha1_CaptchaDiv = browser.Div(Find.ById(IdCaptchaDiv));
                    string linkCaptcha = c_pages_form_cp1_captcha1_CaptchaDiv.Images[0].Src;
                    if (!linkCaptcha.StartsWith("http"))
                    {
                        linkCaptcha = "https://visapoint.eu" + linkCaptcha;
                    }
                    //Chụp captcha Dùng 1 trình duyệt khác
                    IE browserImage = new IE(linkCaptcha);
                    browserImage.CaptureWebPageToFile(fileCapchar);
                    browserImage.AutoClose = true;
                    browserImage.Close();
                    //Lấy captcha
                    string capcharText = getCapchar(fileCapchar);
                    if (!string.IsNullOrEmpty(capcharText))
                    {
                        Div div = browser.Div(Find.ById("cp1_pnlCaptcha"));
                        TextField textFiled = div.TextFields[0];
                        textFiled.Focus();
                        textFiled.KeyPress((char)Keys.Back);
                        textFiled.Click();
                        textFiled.SetAttributeValue("value", "");
                        for (int i = 0; i < capcharText.Length; i++)
                        {
                            textFiled.KeyPress(capcharText[i]);
                            if (i < (capcharText.Length - 1))
                            {
                                textFiled.KeyPress(' ');
                            }
                        }

                    }
                    // 
                    WatiN.Core.Button btnNext = browser.Button(Find.ById(IdNextButton));
                    if (btnNext != null && btnNext.Exists)
                    {
                        //WriteLog("Next Click");
                        StartSubmit = DateTime.Now;
                        btnNext.Click();
                        //Lay time theo tuy chinh tren giao dien
                        if (txtTimeSubmit != null && !string.IsNullOrEmpty(txtTimeSubmit.Text))
                        {
                            TimeSubmit = 60 - int.Parse(txtTimeSubmit.Text);
                        }
                        else
                        {
                            TimeSubmit = (int)Math.Round((double)DateTime.Now.CompareMillisecondTo(StartSubmit) / 1000);
                            TimeSubmit = (TimeSubmit <= 0) ? 1 : TimeSubmit;
                        }
                    }
                    //btnNext = browser.Button(Find.ById("ctl00_cp1_btnNext_input"));
                    WatiN.Core.Button btnPre = browser.Button(Find.ById(IdPreButton));
                    if (btnNext != null && btnNext.Exists && btnPre != null && btnPre.Exists)
                    {
                        WriteLog("Success first");
                        Result = VISAPOINT_RESULT.SUCCESS;
                        OnSuccess(browser);
                    }
                    else
                    {

                        if (btnNext != null && btnNext.Exists)
                        {
                            WriteLog("Capchar not success");
                            btnNext.Click();
                            goto FirstCaptcha;
                        }
                        else
                        {
                            if (btnPre != null && btnPre.Exists)
                            {
                                Element span = browser.Element(Find.ById("cp1_lblNoDatesEmbassyInfo"));
                                if (span != null && span.Exists)
                                {
                                    string regex = "(?<time>\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2})";
                                    Match match = Regex.Match(span.Text.Trim(), regex);
                                    if (match.Success)
                                    {
                                        string time = match.Groups["time"].Value;
                                        DateTime dateCurrentOfVisa = time.ToDateTime();
                                        //Tinh độ chênh lệch giữa time hệ thống và Visapoint
                                        TickBetweenVisapointAndSystem = dateCurrentOfVisa.Ticks - DateTime.Now.Ticks;
                                        WriteLog("TickBetweenVisapointAndSystem: " + TickBetweenVisapointAndSystem);
                                    }
                                    if (txtTimeSubmit != null && !string.IsNullOrEmpty(txtTimeSubmit.Text))
                                    {
                                        TimeSubmit = 60 - int.Parse(txtTimeSubmit.Text);
                                    }
                                    else
                                    {
                                        TimeSubmit = (int)DateTime.Now.CompareMillisecondTo(StartSubmit) / 1000;
                                        TimeSubmit = (TimeSubmit <= 0) ? 1 : TimeSubmit;
                                    }
                                    WriteLog("Not success: " + span.Text.Trim());
                                }
                                //if (TickBetweenVisapointAndSystem != 0)
                                {
                                    if ((btnPre != null && btnPre.Exists))
                                    {
                                        //WriteLog("Waiting Click Back....");
                                        //WriteLog("timeVisa: " + TimeVisapoint.ToString("dd/MM/yyyy HH:mm:ss"));
                                        long timeWating = GetLongTimeWaiting(TimeVisapoint, SecondBeginRun - 10);
                                        //WriteLog("timeWating Click Back: " + timeWating);
                                        if (timeWating > 0)
                                        {
                                            if (!cancellationTokenSource.IsCancellationRequested)
                                            {
                                                cancellationTokenSource.Token.WaitHandle.WaitOne((int)timeWating);
                                                //Thread.Sleep((int)timeWating);
                                            }

                                            //WriteLog("BtnPre Click: ");
                                            StartRun = DateTime.Now;
                                            btnPre.Click();
                                            IsBack = true;
                                            //SecondLoadStartRun = (int)DateTime.Now.CompareMillisecondTo(StartRun) / 1000;
                                            //SecondLoadStartRun = (SecondLoadStartRun <= 0) ? 4 : SecondLoadStartRun;
                                            //SecondBeginRun = 60 - (SecondProcessCaptcha + SecondLoadStartRun + SecondSubmit);
                                        }
                                        else
                                        {
                                            btnPre.Click();
                                        }
                                    }

                                }
                                //btnPre.Click();
                                //btnNext = browser.Button(Find.ById("ctl00_cp1_btnNext_input"));
                                //btnPre = browser.Button(Find.ById("ctl00_cp1_btnPrev_input"));
                            }
                        }
                    WhileRun:
                        while (((btnNext != null && btnNext.Exists) || (btnPre != null && btnPre.Exists)) && Status == VISAPOINT_STATUS.RUNNING)
                        {
                        StartRun:

                            IsBack = false;
                            btnNext = browser.Button(Find.ById(IdNextButton));
                            if ((btnNext != null && btnNext.Exists))
                            {
                                //WriteLog("Waiting....");

                                long timeWating = GetLongTimeWaiting(TimeVisapoint, SecondBeginRun);
                                //WriteLog("timeWating: " + timeWating);
                                if (timeWating > 0)
                                {
                                    if (!cancellationTokenSource.IsCancellationRequested)
                                    {
                                        cancellationTokenSource.Token.WaitHandle.WaitOne((int)timeWating);
                                        //Thread.Sleep((int)timeWating);
                                    }
                                    //WriteLog("btnNext Click: ");
                                    StartRun = DateTime.Now;
                                    if (txtTimeSubmit != null && !string.IsNullOrEmpty(txtTimeSubmit.Text))
                                    {
                                        TimeSubmit = 60 - int.Parse(txtTimeSubmit.Text);
                                    }

                                    WriteLog("StartRun: " + TimeVisapoint.ToString("dd/MM/yyyy HH:mm:ss"));
                                    WriteLog("TimeLoadStartRun: " + TimeLoadStartRun);
                                    WriteLog("TimeSubmit: " + TimeSubmit);
                                    btnNext.Click();
                                    StartCaptcha = DateTime.Now;
                                    if (!IsFixLoadRun)
                                    {
                                        TimeLoadStartRun = (int)DateTime.Now.CompareMillisecondTo(StartRun) / 1000;
                                        TimeLoadStartRun = (TimeLoadStartRun <= 0) ? 4 : TimeLoadStartRun;
                                    }
                                    //WriteLog("SecondLoadStartRun: " + TimeLoadStartRun);
                                    SecondBeginRun = 60 - (TimeProcessCaptchaMAX + TimeLoadStartRun + TimeSubmit);



                                }
                            }
                            c_pages_form_cp1_captcha1_CaptchaDiv = browser.Div(Find.ById(IdCaptchaDiv));
                            if (c_pages_form_cp1_captcha1_CaptchaDiv.Images != null && c_pages_form_cp1_captcha1_CaptchaDiv.Images.Count > 0)
                            {
                                linkCaptcha = c_pages_form_cp1_captcha1_CaptchaDiv.Images[0].Src;
                            }
                            else
                            {
                                if (btnPre.Exists)
                                {
                                    btnPre.Click();
                                    goto StartRun;
                                }

                            }

                            if (!linkCaptcha.StartsWith("http"))
                            {
                                linkCaptcha = "https://visapoint.eu" + linkCaptcha;
                            }
                            WriteLog("Start get Capchar");
                            browserImage = new IE(linkCaptcha);
                            browserImage.AutoClose = true;
                            browserImage.CaptureWebPageToFile(fileCapchar);
                            browserImage.Close();
                            capcharText = getCapchar(fileCapchar);
                            //WriteLog("Done get Capchar");
                            Div div = browser.Div(Find.ById("cp1_pnlCaptcha"));
                            TextField textFiled = div.TextFields[0];
                            textFiled.Focus();
                            textFiled.KeyPress((char)Keys.Back);
                            textFiled.Click();
                            textFiled.SetAttributeValue("value", "");
                            //List<char> list = new List<char>();
                            for (int i = 0; i < capcharText.Length; i++)
                            {
                                textFiled.KeyPress(capcharText[i]);
                                if (i < (capcharText.Length - 1))
                                {
                                    textFiled.KeyPress(' ');
                                }
                            }
                            //Sau khi dien xong capchar thi waiting de click next
                            //Time captcha
                            Boolean waiting = true;


                            int TimeCaptcha = (int)Math.Round((double)DateTime.Now.CompareMillisecondTo(StartCaptcha) / 1000);
                            WriteLog("TimeCaptcha: " + TimeCaptcha);
                            if (TimeCaptcha > (TimeProcessCaptchaMAX))
                            {
                                goto StartRun;

                            }
                            if (waiting)
                            {
                                WriteLog("timeVisaCurrent: " + TimeVisapoint.ToString("dd/MM/yyyy HH:mm:ss"));

                                long timeWatingClickNext = GetLongTimeWaiting(TimeVisapoint, (60 - TimeSubmit));
                                //WriteLog("timeWatingClickNext: " + timeWatingClickNext);
                                if ((int)timeWatingClickNext / 1000 > TimeProcessCaptchaMAX)
                                {
                                    goto StartRun;
                                }

                                if (timeWatingClickNext > 0)
                                {

                                    //int TimeWaiting = (int)timeWatingClickNext / 1000;
                                    //TimeWaiting = (TimeWaiting + TimeCaptcha >= 20) ? (19 - TimeCaptcha) * 1000 : (int)timeWatingClickNext;
                                    WriteLog("timeWatingClickNext: " + timeWatingClickNext);
                                    if (!cancellationTokenSource.IsCancellationRequested)
                                    {
                                        cancellationTokenSource.Token.WaitHandle.WaitOne((int)timeWatingClickNext);
                                        //Thread.Sleep((int)timeWating);
                                    }
                                    //WriteLog("btnNext Click: ");
                                    StartRun = DateTime.Now;

                                    WriteLog("StartNext: " + TimeVisapoint.ToString("dd/MM/yyyy HH:mm:ss"));
                                    StartSubmit = DateTime.Now;
                                    btnNext = browser.Button(Find.ById(IdNextButton));
                                    btnNext.Click();
                                    if (txtTimeSubmit != null && !string.IsNullOrEmpty(txtTimeSubmit.Text))
                                    {
                                        TimeSubmit = 60 - int.Parse(txtTimeSubmit.Text);
                                    }
                                    else
                                    {
                                        TimeSubmit = (int)Math.Round((double)DateTime.Now.CompareMillisecondTo(StartSubmit) / 1000);
                                        TimeSubmit = (TimeSubmit <= 0) ? 1 : TimeSubmit;
                                    }
                                }
                            }

                            if (btnPre.Exists)
                            {

                                Element span = browser.Element(Find.ById("cp1_lblNoDatesEmbassyInfo"));
                                if (span != null && span.Exists)
                                {
                                    string regex = "(?<time>\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2})";
                                    Match match = Regex.Match(span.Text.Trim(), regex);
                                    if (match.Success)
                                    {
                                        string time = match.Groups["time"].Value;
                                        DateTime dateCurrentOfVisa = time.ToDateTime();
                                        //WriteLog("dateCurrentOfVisa: " + dateCurrentOfVisa.ToString("dd/MM/yyyy HH:mm:ss"));
                                        TickBetweenVisapointAndSystem = dateCurrentOfVisa.Ticks - DateTime.Now.Ticks;
                                        //WriteLog("TickBetweenVisapointAndSystem: " + TickBetweenVisapointAndSystem);
                                    }
                                    //Tinh lai time cho qua trinh xu ly

                                    //WriteLog("SecondSubmit: " + TimeSubmit);
                                    WriteLog("Not success: " + span.Text.Trim());
                                }

                                if (TickBetweenVisapointAndSystem != 0)
                                {
                                    if ((btnPre != null && btnPre.Exists))
                                    {
                                        //WriteLog("Waiting Click Back....");
                                        //WriteLog("timeVisa: " + TimeVisapoint.ToString("dd/MM/yyyy HH:mm:ss"));
                                        long timeWating = GetLongTimeWaiting(TimeVisapoint, SecondBeginRun - 10);
                                        //WriteLog("timeWating Click Back: " + timeWating);
                                        if (timeWating > 0)
                                        {
                                            if (!cancellationTokenSource.IsCancellationRequested)
                                            {
                                                cancellationTokenSource.Token.WaitHandle.WaitOne((int)timeWating);
                                                //Thread.Sleep((int)timeWating);
                                            }
                                            //WriteLog("BtnPre Click: ");
                                            StartRun = DateTime.Now;
                                            btnPre.Click();
                                            IsBack = true;
                                        }
                                        else
                                        {
                                            btnPre.Click();
                                        }
                                    }

                                }


                            }

                            if (btnNext != null && btnNext.Exists && btnPre != null && btnPre.Exists)
                            {
                                WriteLog("Success in While");
                                Result = VISAPOINT_RESULT.SUCCESS;
                                break;
                            }
                            btnNext = browser.Button(Find.ById(IdNextButton));
                            btnPre = browser.Button(Find.ById(IdPreButton));
                        }

                        if (Result == VISAPOINT_RESULT.SUCCESS)
                        {
                            WriteLog("Visapoint Success");
                            OnSuccess(browser);
                            //MessageBox.Show("Register Success");
                        }
                        else
                        {
                            if (Status == VISAPOINT_STATUS.RUNNING)
                            {
                                btnNext = browser.Button(Find.ById(IdNextButton));
                                btnPre = browser.Button(Find.ById(IdPreButton));
                                int count = 0;
                                WriteLog("Vao xác định lại btn pre");
                                while ((btnNext == null || !btnNext.Exists) && (btnPre == null || !btnPre.Exists) && count < 5)
                                {
                                    count++;
                                    Thread.Sleep(1000);
                                    btnNext = browser.Button(Find.ById(IdNextButton));
                                    btnPre = browser.Button(Find.ById(IdPreButton));
                                }
                                if (btnPre.Exists)
                                {
                                    WriteLog("Ton tai btnPre");
                                    Element span = browser.Element(Find.ById("cp1_lblNoDatesEmbassyInfo"));
                                    if (span != null && span.Exists)
                                    {
                                        string regex = "(?<time>\\d{1,2}/\\d{1,2}/\\d{4} \\d{1,2}:\\d{1,2}:\\d{1,2})";
                                        Match match = Regex.Match(span.Text.Trim(), regex);
                                        if (match.Success)
                                        {
                                            string time = match.Groups["time"].Value;
                                            DateTime dateCurrentOfVisa = time.ToDateTime();
                                            WriteLog("dateCurrentOfVisa: " + dateCurrentOfVisa.ToString("dd/MM/yyyy HH:mm:ss"));
                                            //Tinh độ chênh lệch giữa time hệ thống và Visapoint
                                            TickBetweenVisapointAndSystem = dateCurrentOfVisa.Ticks - DateTime.Now.Ticks;
                                            WriteLog("TickBetweenVisapointAndSystem: " + TickBetweenVisapointAndSystem);
                                        }
                                        if (txtTimeSubmit != null && !string.IsNullOrEmpty(txtTimeSubmit.Text))
                                        {
                                            TimeSubmit = 60 - int.Parse(txtTimeSubmit.Text);
                                        }
                                        else
                                        {
                                            TimeSubmit = (int)DateTime.Now.CompareMillisecondTo(StartSubmit) / 1000;
                                            TimeSubmit = (TimeSubmit <= 0) ? 1 : TimeSubmit;
                                        }
                                        WriteLog("Not success: " + span.Text.Trim());
                                    }
                                    //WriteLog("Waiting Click Back....");
                                    //WriteLog("timeVisa: " + TimeVisapoint.ToString("dd/MM/yyyy HH:mm:ss"));
                                    long timeWating = GetLongTimeWaiting(TimeVisapoint, SecondBeginRun - 10);
                                    //WriteLog("timeWating Click Back: " + timeWating);
                                    if (timeWating > 0)
                                    {
                                        Thread.Sleep((int)timeWating);
                                        WriteLog("BtnPre Click: ");
                                        StartRun = DateTime.Now;
                                        btnPre.Click();
                                        IsBack = true;

                                    }
                                    else
                                    {
                                        btnPre.Click();
                                    }
                                    goto WhileRun;
                                }
                                else if (btnNext.Exists)
                                {
                                    WriteLog("Ton tai btnNext");
                                    goto WhileRun;
                                }
                                browser.Close();

                            }
                        }
                    }

                }
            }
            catch (System.Exception ex)
            {
                WriteLog("Error: " + ex.Message);
                if (Status == VISAPOINT_STATUS.RUNNING)
                {
                    browser.Close();
                    Start();
                }

            }
            finally
            {
                if (browser != null)
                {
                    browser.Close();
                    //browser.Dispose();
                }
            }
        }
        private void OnSuccess(IE browser)
        {
            WriteLog("Begin Input Info");
            browser.BringToFront();
            //browser.AutoClose = false;
            WatiN.Core.Button btnNext = browser.Button(Find.ById(IdNextButton));
            WatiN.Core.Button btnPre = browser.Button(Find.ById(IdPreButton));



            Element label = browser.Element(Find.ByFor("cp1_rblDate_0"));
            WriteLog("Time hen: " + label.InnerHtml.Trim());
            btnNext = browser.Button(Find.ById("ctl00_cp1_btnNext_input"));
            btnNext.Click();
        Next1:

            //Thiet lap ten
            TextField txtName = browser.TextField(Find.ById("ctl00_cp1_txtFirstName"));
            txtName.TypeText(AppointmentCurrent.FirstName);
            SendKeys.SendWait("{TAB}");

            ////Thiet lap ho
            TextField txtFamilyName = browser.TextField(Find.ById("ctl00_cp1_txtFamilyName"));
            txtFamilyName.TypeText(AppointmentCurrent.FamilyName);
            SendKeys.SendWait("{TAB}");

            ////thiet lap ngay sinh
            TextField txtNgaysinh = browser.TextField(Find.ById("ctl00_cp1_txtBirthDate_dateInput"));
            //txtNgaysinh.Focus();
            //txtNgaysinh.KeyPress((char)Keys.Back);
            txtNgaysinh.Click();
            txtNgaysinh.TypeText(AppointmentCurrent.DateOfBirth);
            SendKeys.SendWait("{TAB}");
            SendKeys.SendWait("{TAB}");

            Div divLanguague = browser.Div(Find.ById("ctl00_cp1_ddSex"));
            divLanguague.Button(Find.ByClass("rcbActionButton")).Click();

            Element elementLanguague = browser.Div(Find.ById("ctl00_cp1_ddSex_DropDown")).Element(Find.ByText(AppointmentCurrent.Gender));
            elementLanguague.Click();
            SendKeys.SendWait("{TAB}");

            //Nhan tiep tuc

            WriteLog("Nhan Next1");
            btnNext = browser.Button(Find.ById(IdNextButton));

            btnNext.Click();
            WriteLog("Nhap ho chieu");
            TextField txtPassportNumber = browser.TextField(Find.ById("ctl00_cp1_txtPassportNumber"));
            if (txtPassportNumber == null || !txtPassportNumber.Exists)
            {
                goto Next1;
            }
            txtPassportNumber.TypeText(AppointmentCurrent.PassportNumber);

            TextField txtEmail = browser.TextField(Find.ById("ctl00_cp1_txtEmail"));
            txtEmail.TypeText(AppointmentCurrent.Email);
        InputPhoneNumber:
            TextField txtPhoneNumber = browser.TextField(Find.ById("ctl00_cp1_txtPhone"));
            txtPhoneNumber.Focus();
            txtPhoneNumber.Click();
            txtPhoneNumber.KeyPress((char)Keys.Back);
            txtPhoneNumber.TypeText(AppointmentCurrent.PhoneNumber);

            btnNext.Click();
            if (txtPhoneNumber.Exists)
            {
                WriteLog("Nhap lai so dien thoai");
                goto InputPhoneNumber;
            }
            WatiN.Core.Button btnSend = browser.Button(Find.ById("ctl00_cp1_btnSend_input"));
            btnSend.Click();
            browser.Close();

            Status = VISAPOINT_STATUS.STOP;
            WriteLog("End Input Info");
            sendEmail("tuyennv.haui@gmail.com|namhieu@gmail.com", "Đăng ký visa thành công", AppointmentCurrent.ToMailBody());
            Visapoint.Alert("Success");
        }
        public void Stop()
        {
            Status = VISAPOINT_STATUS.STOP;
            timer.Stop();
            captchaSocket.Close();
            browser.Close();
        }
        private void WriteLog(string message)
        {
            if (Visapoint != null)
            {
                Visapoint.WriteLog(message);
            }
        }
        private static System.Drawing.Image cropImage(System.Drawing.Image img, Rectangle cropArea)
        {
            Bitmap bmpImage = new Bitmap(img);
            return bmpImage.Clone(cropArea, bmpImage.PixelFormat);
        }

        public byte[] imageToByteArray(System.Drawing.Image imageIn)
        {
            MemoryStream ms = new MemoryStream();
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            return ms.ToArray();
        }
        //public string getCapchar(string PathFile)
        //{
        //    WriteLog("Start Captcha: ");
        //    System.Drawing.Image image = System.Drawing.Image.FromFile(PathFile);
        //    try
        //    {
        //        Client client = (Client)new SocketClient("hieupn", "abCd1234");

        //        Captcha captcha = client.Decode(imageToByteArray(cropImage(image, new Rectangle(new Point(0, 0), new Size(250, 60)))), 20000);
        //        if (captcha != null && captcha.Solved && captcha.Correct)
        //        {
        //            WriteLog("Captcha: " + captcha.Text);
        //            image.Dispose();
        //            return captcha.Text.ToUpper();
        //        }
        //    }
        //    catch (DeathByCaptcha.Exception ex)
        //    {
        //        WriteLog("Error Captcha: " + ex.Message);
        //        if (ex.Message.Equals("CAPTCHA was rejected due to service overload"))
        //        {
        //            if (!cancellationTokenSource.IsCancellationRequested)
        //            {
        //                cancellationTokenSource.Token.WaitHandle.WaitOne(2000);
        //                return getCapchar(PathFile);
        //                //Thread.Sleep((int)timeWating);
        //            }
        //            ;
        //        }
        //    }
        //    finally
        //    {

        //        image.Dispose();
        //        File.Delete(PathFile);
        //    }
        //    return "";
        //}
        public string getCapchar(string PathFile)
        {
            WriteLog("Start Captcha: ");
            string PathFileCrop = Application.StartupPath + "\\captcha_crop.jpg";
            System.Drawing.Image image = System.Drawing.Image.FromFile(PathFile);
            try
            {
                System.Drawing.Image imgCrop = cropImage(image, new Rectangle(new Point(0, 0), new Size(250, 60)));
                imgCrop.Save(PathFileCrop);
                CaptchaSolver solver = new CaptchaSolver();
                imgCrop.Dispose();
                if (solver.SolveCaptcha(PathFileCrop))
                {
                    string CaptchaText = solver.LastResponseText;
                    WriteLog("Captcha: " + CaptchaText);
                    return CaptchaText;
                }

            }
            catch
            {

            }
            finally
            {
                image.Dispose();
                File.Delete(PathFile);
                File.Delete(PathFileCrop);
            }
            return "";
        }
        private long GetLongTimeWaiting(DateTime time, int secondStart)
        {
            long second = time.Second;
            if (second == secondStart)
                return 0;
            if (second > secondStart)
            {
                DateTime TimeTemp = time.AddMinutes(1).ToString("dd/MM/yyyy HH:mm:" + secondStart).ToDateTime();
                long longMiniseconds = (TimeTemp.Ticks - time.Ticks) / TimeSpan.TicksPerMillisecond;
                return longMiniseconds;
            }
            else
            {
                DateTime TimeTemp = time.ToString("dd/MM/yyyy HH:mm:" + secondStart).ToDateTime();
                long longMiniseconds = (TimeTemp.Ticks - time.Ticks) / TimeSpan.TicksPerMillisecond;
                return longMiniseconds;
            }
        }
        public void Run()
        {

            //client.StartClient();

            //Status = VISAPOINT_STATUS.RUNNING;
            //client.onReceive += new AsynchronousClient.OnReceive(OnCommand);
            Thread t = new Thread(new ThreadStart(Start));
            t.ApartmentState = ApartmentState.STA;
            t.Start();
            timer.Start();

        }
        public void OnCommand(string command)
        {
            if (command == Command.StartVisapoint)
            {
                Status = VISAPOINT_STATUS.RUNNING;
                Thread t = new Thread(new ThreadStart(Start));
                t.ApartmentState = ApartmentState.STA;
                t.Start();

            }
            else if (command == Command.StopVisapoint)
            {
                Stop();

            }
            else if (command == Command.CloseVisapoint)
            {
                Stop();
                client.Close();
                if (Visapoint != null)
                {
                    Visapoint.CloseForm();
                }
            }
        }
        public void SendData(string data)
        {
            client.Send(data);
        }
        public void Close()
        {
            Status = VISAPOINT_STATUS.STOP;
            cancellationTokenSource.Cancel();
            if (browser != null)
            {
                browser.Close();
            }
        }
        //public static void sendMail(string ListMailTo, string Subject, string Body)
        //{
        //    try
        //    {
        //        MailMessage mail = new MailMessage();
        //        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

        //        mail.From = new MailAddress("tuyenv.haui@gmail.com");
        //        foreach (var item in ListMailTo.Split('|'))
        //        {
        //            mail.To.Add(item);
        //        }

        //        mail.Subject = Subject;
        //        mail.Body = Body;

        //        SmtpServer.Port = 587;

        //        SmtpServer.EnableSsl = true;
        //        SmtpServer.UseDefaultCredentials = true;
        //        SmtpServer.Credentials = new System.Net.NetworkCredential("tuyenkhmt2k3@gmail.com", "33649326");
        //        SmtpServer.Send(mail);
        //    }
        //    catch (System.Exception)
        //    {

        //    }

        //}
        public static string sendEmail(string ListMailTo, string subject, string body)
        {
            string result = "";
            string senderID = "tuyenkhmt2k3@gmail.com";// use sender’s email id here..
            const string senderPassword = "33649326"; // sender password here
            try
            {
                SmtpClient smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com", // smtp server address here
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    Credentials = new System.Net.NetworkCredential(senderID, senderPassword),
                    Timeout = 30000,
                };
                MailMessage mail = new MailMessage();
                mail.From = new MailAddress("tuyennv.haui@gmail.com");
                foreach (var item in ListMailTo.Split('|'))
                {
                    mail.To.Add(item);
                }

                mail.Subject = subject;
                mail.Body = body;
                smtp.Send(mail);
            }
            catch (System.Exception ex)
            {
                result = "Error sending email.!!!";
            }
            return result;
        }
    }
}
